var changeList = [];
showLoading();

//购物车控制器
function buyCar($scope, $http, $timeout) {
	//获得圈子名字
	$scope.circleName = readData(localStorage.circleName);
	$scope.isshow = true;
	//初始化请求服务器
	$scope.init = function() {
		$scope.nameId = 'name56Id';
		var buyCar;
		//判断购物车是否为空
		if (localStorage.buyCar == null || localStorage.buyCar == "undefined" || readDataBuyCar(localStorage.buyCar) == "") {
			buyCar = {};
		} else {
			//读取购物车
			buyCar = readDataBuyCar(localStorage.buyCar);
			buyCar = eval('(' + buyCar + ')');
		}
		var productGroup = {
			list: []
		};
		//根据导购ID获得本圈子购物车信息
		if (buyCar[readData(localStorage.guideId)] != "" && buyCar[readData(localStorage.guideId)] != null) {
			productGroup['list'] = buyCar[readData(localStorage.guideId)];
		}
		//请求服务器获得购物车详细信息
		url = getUrl("21buycar");
		header = getHeader();
		datas = 'json=' + JSON.stringify(productGroup);
		$http({
			method: 'POST',
			url: url,
			headers: header,
			timeout: 10000,
			//params : params
			data: datas
		}).success(function(data, status, headers, config) {
			var Buycarlist = [];
			var buyId = [];
			if (data.obj) {
				var sBuylist = data.obj.list;
				for (i in sBuylist) {
					//根据服务车对象商品数量为0的获取到购物车中已经失效的信息
					if (sBuylist[i].number == 0) {
						buyId.push(sBuylist[i].id);
						continue;
					} else {
						//下列为购物车内没有失效的商品
						var exchangePrice = 0;
						//获取换购商品的价格
						if (sBuylist[i].exchangeList) {
							for (var j in sBuylist[i].exchangeList) {
								exchangePrice += parseFloat(sBuylist[i].exchangeList[j].price);
							}
						}
						var piceal = (parseInt(sBuylist[i].number) * parseFloat(sBuylist[i].nowPrice) + exchangePrice).toFixed(2);
						var yincang, imageurl;
						if (sBuylist[i].priceName) {
							yincang = true;
						} else {
							yincang = false;
						}
						if (sBuylist[i].picture) {
							imageurl = sBuylist[i].picture;
						} else {
							imageurl = '../../image/small.png';
						}
						//写入购物车列表用于显示
						Buycarlist.push({
							id: sBuylist[i].id,
							name: sBuylist[i].name,
							picture: imageurl,
							number: sBuylist[i].number,
							price: sBuylist[i].price,
							nowPrice: sBuylist[i].nowPrice,
							specColorpr: sBuylist[i].specColorpr,
							specSizepr: sBuylist[i].specSizepr,
							specModel: sBuylist[i].specModel,
							specSpec: sBuylist[i].specSpec,
							priceName: sBuylist[i].priceName,
							priceall: piceal,
							deposit: sBuylist[i].deposit,
							hide: yincang,
							giftList: sBuylist[i].giftList,
							exchangeList: sBuylist[i].exchangeList,
							promotionList: sBuylist[i].promotionList,
							isBuy: sBuylist[i].isBuy
						});
					}
				}
				//删除本地购物车
				for (var i = 0; i < buyId.length; i++) {
					XiagoodsDel(buyId[i], readData(localStorage.guideId));
				}
				if (buyId.length > 0) {
					mui.alert("购物车中存在商品已经下架")
				}
				//根据购物车列表是否为空判断是否显示提示
				if (Buycarlist.length <= 0) {
					$scope.isshow = false;
				} else {
					$scope.isshow = true;
				}
				var produ = Buycarlist;
				//判断规格尺寸显示隐藏
				for (var i = 0; i < produ.length; i++) {
					if (produ[i].specColorpr) {
						produ[i].ngcolor = "false";
					} else {
						produ[i].ngcolor = "true";
					}
					if (produ[i].specSizepr) {
						produ[i].ngsize = "false";
					} else {
						produ[i].ngsize = "true";
					}
					if (produ[i].specSpec) {
						produ[i].ngspec = "false";
					} else {
						produ[i].ngspec = "true";
					}
					if (produ[i].specModel) {
						produ[i].ngmodel = "false";
					} else {
						produ[i].ngmodel = "true";
					}
				}
				$scope.buyCars = produ;
				//下边用来计算总价格
				$timeout($scope.goodsSum, 500);
				$timeout($scope.goodsSum, 1500);
			} else {
				$scope.comment = null;
			};
			removeLoading()
		}).error(function(data, status, headers, config) {
			console.log("buyCar is erro");
		});
	}
	$scope.init();
	//购物车数量控制
	$scope.Num = function(goods, num) {
			//var textnum = document.getElementById("textnum");
			//var numI = parseFloat(textnum.value) + num;
			var newNum = goods.number;
			if (num == '0') {
				newNum = newNum - 1
			} else {
				newNum = newNum + 1
			}
			if (newNum == 0) {
				return;
			} else {
				//textnum.value = numI;
				//newNum = newNum.toString();
				//更新本地购物车信息
				goodsNum(goods.id, readData(localStorage.guideId), newNum, goods.specSizepr, goods.specColorpr, goods.specModel, goods.specSpec);
				//更新界面信息
				buyCar = $scope.buyCars;
				var flag = '1';
				for (x in buyCar) {
					var jsonObj = buyCar[x];
					if (jsonObj.id == goods.id && jsonObj.specSizepr == goods.specSizepr && jsonObj.specColorpr == goods.specColorpr && jsonObj.specModel == goods.specModel && jsonObj.specSpec == goods.specSpec && flag == '1') {
						buyCar[x]['number'] = newNum;
						flag = '0';
					}
				};
				var exchangePrice = 0;
				if (goods.exchangeList) {
					for (var j in goods.exchangeList) {
						exchangePrice += parseFloat(goods.exchangeList[j].price);
					}
				}
				var xiaojiId = $scope.nameId + goods.id + goods.specColorpr + goods.specSizepr + goods.specModel + goods.specSpec;
				document.getElementById(xiaojiId).innerHTML = '小计:￥' + (parseFloat(goods.nowPrice) * parseInt(newNum) + exchangePrice).toFixed(2);
				//刷新界面购物车信息
				$scope.buyCars = buyCar;
				//更新汇总结果
				if (document.getElementById(goods["id"] + goods["specColorpr"] + goods["specSizepr"] + goods["specModel"] + goods["specSpec"]).checked == true) {
					if (num == '0') {
						$scope.sumPrice = (parseFloat($scope.sumPrice) - parseFloat(goods.nowPrice)).toFixed(2);
						$scope.sumNumber = parseFloat($scope.sumNumber) - 1;
					} else {
						$scope.sumPrice = (parseFloat($scope.sumPrice) + parseFloat(goods.nowPrice)).toFixed(2);
						$scope.sumNumber = parseFloat($scope.sumNumber) + 1;
					}
				}
				$scope.init();
				//api.showProgress();
				//刷新购物车数量
				refershBycar();
			}
		}
		//删除购物车
	$scope.deleteGoods = function(gid, gsize, gcolor, gmodel, gspec) {
		mui.confirm('是否将此商品移出购物车', '删除商品', ['确定', '取消'], function(ret) {
			if (ret.index == 0) {
				//更新本地购物车
				goodsDel(gid, readData(localStorage.guideId), gsize, gcolor, gmodel, gspec);
				buyCar = $scope.buyCars;
				var flag = '1';
				for (x in buyCar) {
					var jsonObj = buyCar[x];
					if (jsonObj.id == gid && jsonObj.specSizepr == gsize && jsonObj.specColorpr == gcolor && jsonObj.specModel == gmodel && jsonObj.specSpec == gspec && flag == '1') {
						buyCar.splice(x, 1);
						flag = '0';
					}
				};
				//刷新界面购物车信息
				$scope.$apply($scope.buyCars = buyCar);
				$scope.$apply($scope.goodsSum())
					//购物车商品数量
				if (localStorage.buyCar && readDataBuyCar(localStorage.buyCar) != "") {
					var buyCar = eval('(' + readDataBuyCar(localStorage.buyCar) + ')');
					var buyCarGuide = buyCar[readData(localStorage.guideId)];
					var num = 0
						//遍历购物车，查看商品是否存在（同型号同颜色）
					for (x in buyCarGuide) {
						num = num + parseInt(buyCarGuide[x]['number'])
					}
					if (num <= 0) {
						$scope.$apply($scope.isshow = false);
					}
				}
				//刷新购物车数量
				refershBycar();
			}
		})
	}
	$scope.jiesuan = function() {
			//获取li相关信息
			var jsd = [];
			var ul = document.getElementById("product").getElementsByTagName("li");
			for (var i = 0; i < ul.length; i++) {
				var goodsJson = ul[i].getAttribute("value");
				goodsJson = eval('(' + goodsJson + ')');
				if (document.getElementById(goodsJson["id"] + goodsJson["specColorpr"] + goodsJson["specSizepr"] + goodsJson["specModel"] + goodsJson["specSpec"]).checked == true) {
					jsd.push(goodsJson);
				}
			}
			if (jsd.length == 0) {
				var num = 0
				if (localStorage.buyCar && readDataBuyCar(localStorage.buyCar) != "") {
					var buyCar = eval('(' + readDataBuyCar(localStorage.buyCar) + ')');
					var buyCarGuide = buyCar[readData(localStorage.guideId)];
					//遍历购物车，查看商品是否存在（同型号同颜色）
					for (x in buyCarGuide) {
						num = num + parseInt(buyCarGuide[x]['number'])
					}
				}
				if (num == 0) {
					mui.toast('购物车中没有商品,先去逛逛吧');
				} else {
					mui.toast("请先选择需要结算的商品");
				}
			} else {
				jsd = {
					list: jsd
				};

				localStorage.order = writeData(JSON.stringify(jsd));
				OpenNewWin({
					id: "conformOrder.html",
					url: "conformOrder.html"
				})
			}
		}
		//计算商品总价钱
		//type类型字符串用来判断是否点击的是最上边的input,根据此变量做相应处理
	$scope.goodsSum = function(type) {
			var ul = document.getElementById("product").getElementsByTagName("li");
			var maxinput = document.getElementById("a");
			var sumNum = 0;
			var sumPri = 0;
			if ('max' == type) {
				if (maxinput.checked) {
					for (var i = 0; i < ul.length; i++) {
						ul[i].getElementsByTagName("input")[0].checked = true;
					}
				} else {
					for (var i = 0; i < ul.length; i++) {
						ul[i].getElementsByTagName("input")[0].checked = false;
					}
				}
			} else {
				var sum = 0
				for (var i = 0; i < ul.length; i++) {
					if (ul[i].getElementsByTagName("input")[0].checked == false) {
						maxinput.checked = false;
					} else {
						sum++;
					}
					if (sum == ul.length) {
						maxinput.checked = true;
					}
				}
			}
			for (var i = 0; i < ul.length; i++) {
				var goodsJson = ul[i].getAttribute("value");
				goodsJson = eval('(' + goodsJson + ')');
				if (document.getElementById(goodsJson["id"] + goodsJson["specColorpr"] + goodsJson["specSizepr"] + goodsJson["specModel"] + goodsJson["specSpec"]).checked == true) {
					var exchangePrice = 0;
					if (goodsJson.exchangeList) {
						for (var j in goodsJson.exchangeList) {
							exchangePrice += parseFloat(goodsJson.exchangeList[j].price);
						}
					}
					sumNum = sumNum + parseFloat(goodsJson.number);
					sumPri = sumPri + (parseFloat(goodsJson.number) * parseFloat(goodsJson.nowPrice) + exchangePrice);
				}
			}
			$scope.sumPrice = sumPri.toFixed(2);
			$scope.sumNumber = sumNum;
		}
		//换购商品功能 获取换购列表 list为被换购的商品以备后续查找所要插入元素的位置
	$scope.changeGoodsFun = function(list) {
			//获取对象 mask 弹出页
			api.showProgress();
			var changeGood = document.getElementById("changeGood");
			var mask = document.getElementById("mask");
			var adUrl = getUrl("80exchageProducts");
			$scope.listGood = list;
			//获得已选择的换购商品数组列表
			//$scope.changeList=list.exchangeList;
			if (list.exchangeList) {
				changeList = list.exchangeList.concat();
			} else {
				changeList = [];
			}
			//判断现在已经勾选的换购商品
			$scope.checkgoodsNum = changeList.length;
			paramsAd = {
				productId: list.id
			}
			$http({
				method: 'POST',
				url: adUrl,
				timeout: 10000,
				params: paramsAd
			}).success(function(data, status, headers, config) {

				if (data.code == 0) {
					var clist = changeList;
					var dlist = data.obj.list;
					//遍历找到已经勾选的商品 改变样式
					for (var i = 0; i < dlist.length; i++) {
						for (var j = 0; j < clist.length; j++) {
							if (dlist[i].id == clist[j].id) {
								dlist[i].classactive = "lisactive"
							}
						}
					}
					$scope.changeGoods = dlist;
					$scope.limitNum = data.obj.quotaNumber;
					mask.style.display = "block";
					api.hideProgress();
					setTimeout(function() {
						mask.className = "mask mask-active";
						changeGood.className = "changeGood changeGood-active"
					}, 100)
				}
			});
		}
		//确定功能
	$scope.ensure = function() {
			var good = $scope.listGood;
			for (var i = 0; i < $scope.buyCars.length; i++) {
				buygood = $scope.buyCars[i];
				if (buygood.id == good.id && buygood.specColorpr == good.specColorpr && buygood.specSizepr == good.specSizepr && buygood.specModel == good.specModel && buygood.specSpec == good.specSpec) {
					var pricetotal = 0;
					for (var j = 0; j < changeList.length; j++) {
						pricetotal += parseFloat(changeList[j].price);
					}
					var money = (good.number * parseFloat(good.nowPrice) + pricetotal).toFixed(2);
					$scope.buyCars[i].priceall = money;
					$scope.buyCars[i].exchangeList = changeList;
				}
			}
			var exchangeID = [];
			for (var i in changeList) {
				exchangeID.push({
					id: changeList[i].id
				})
			}
			goodsAdd(good.id, good.number, readData(localStorage.guideId), good.specSizepr, good.specColorpr, good.specModel, good.specSpec, exchangeID)
			$timeout($scope.goodsSum, 500);
			$scope.hideMask();
		}
		//隐藏换购
	$scope.hideMask = function() {
			var changeGood = document.getElementById("changeGood");
			var mask = document.getElementById("mask");
			mask.className = "mask";
			changeGood.className = "changeGood";
			setTimeout(function() {
				mask.style.display = "none";
			}, 100)
		}
		//点击列表功能
	$scope.clickGood = function(good) {
		var chageGoodList = document.getElementById("chageGoodList");
		var lis = chageGoodList.getElementsByTagName("li");
		var hasClassNum = 0;
		var obj = document.getElementById(good.id);
		for (var i = 0; i < lis.length; i++) {
			if (lis[i].classList.contains("lisactive")) {
				hasClassNum++;
			}
		}
		var exchengelist = changeList;
		if (obj.classList.contains("lisactive")) {
			obj.classList.remove("lisactive")
			for (var j = 0; j < exchengelist.length; j++) {
				if (exchengelist[j].id == good.id) {
					exchengelist.splice(j, 1);
				}
			}
		} else {
			if ($scope.limitNum == hasClassNum) {
				mui.toast(
					'换购商品前请取消已选择商品'
				);
			} else {
				obj.classList.add("lisactive")
				exchengelist.push(good);
			}
		}
		changeList = exchengelist;
		$scope.checkgoodsNum = exchengelist.length
	}
	window.addEventListener("refreshBuyCar", function() {
		$scope.init();
	}, false)
}

function openShop() {
	OpenNewWin({
		id: "dianpu.html",
		url: "dianpu.html"
	})
}